package blog.farb.top.springbootforredis.service;

import blog.farb.top.springbootforredis.entity.Stock;
import blog.farb.top.springbootforredis.repo.StockRedisRepo;
import blog.farb.top.springbootforredis.repo.StockRepo;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

@Service
public class StockServiceImpl implements StockService {
    private static final String REDIS_KEY_PREFIX = "stock:";

    @Resource
    private StockRedisRepo stockRedisRepo;

    @Resource
    private StockRepo stockRepo;

    @Override
    public Stock getStockById(int id) {
        String key = REDIS_KEY_PREFIX + id;
        Stock stock = stockRedisRepo.getStockById(key);
        if (stock != null) {
            System.out.println("Get stock from Redis");
            return stock;
        }
        System.out.println("Get stock from DB");
        stock = stockRepo.findById(id).orElse(null);
        stockRedisRepo.addStock(key, stock, 1000 * 60 * 10);
        return stock;
    }
}
